package lion.framework.core.db.datasource;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import lion.dev.exception.DBException;
import lion.dev.lang.MapJ;
import lion.framework.core.db.anno.DataSourceProvider;

/**
 * jndi Datasource 提供者<br/>
 * 配置：1、resource:资源url 如java:/comp/env/jdbc/postgres
 * 
 * <pre>
 * time   2013年8月6日
 * mail   hl_0074@sina.com
 * </pre>
 * 
 * @author lion
 */
@DataSourceProvider("jndi")
public class JNDIDataSourceProvider implements IDataSourceProvider {

	private MapJ config;

	public JNDIDataSourceProvider(MapJ config) {

		this.config = config;
	}

	@Override
	public DataSource getDataSource() {

		try {
			Context initContext = new InitialContext();
			DataSource ds = (DataSource) initContext.lookup(this.config.getString("resource"));
			return ds;
		} catch (NamingException e) {
			throw new DBException("init datasource failed", e);
		}
	}

}
